package com.faryangsh.algorithm.basicfor1;

/**
 * 队列
 * --用列表实现
 *
 * Created by 杨志远 on 2017/8/18
 * email faryangsh@163.com.
 */
public class QueueInNode<Item> {
    Node frist;
    Node last;
    int length;

    private class Node {
        Item item;
        Node next;
    }

    public boolean isEmpty() {
        return frist == null;
    }

    private void enqueue(Item item) {
        Node oldItem = last;
        last = new Node();
        last.item = item;
        if (isEmpty()) {
            frist = last;
            length = 1;
        } else {
            oldItem.next = last;
            length++;
        }
    }

    public Item dequeue() {
        Item result = frist.item;
        frist = frist.next;
        length--;
        return result;
    }

    public int size() {
        return length;
    }

    public static void main(String[] args) {
        QueueInNode<String> queue = new QueueInNode<>();
        queue.enqueue("one");
        queue.enqueue("two");
        queue.enqueue("three");
        System.out.println(queue.size());
        System.out.println(queue.dequeue());
        System.out.println(queue.size());
        queue.enqueue("four");
        System.out.println(queue.dequeue());
        System.out.println(queue.size());
        System.out.println(queue.dequeue());
        System.out.println(queue.size());
        System.out.println(queue.dequeue());
        System.out.println(queue.size());
    }
}
